package com.tecode.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tecode.bean.Music;
import com.tecode.bean.User;
import com.tecode.bean.UserFans;
import com.tecode.mapper.UserMapper;
import com.tecode.service.UserService;
import com.tecode.util.DateUtil;
import com.tecode.util.MessageUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.*;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Map> getWorksByid(Integer id) {
        return userMapper.getWorksByid(id);
    }

    @Override
    public Integer selectMusicUserWorksNumById(Integer id) {
        return userMapper.selectMusicUserWorksNumById(id);
    }

    @Override
    public List<Map> selectMusicByCId() {
        return userMapper.selectMusicByCId();
    }

    @Override
    public List<Map> selectUserByTypeId() {
        return userMapper.selectUserByTypeId();
    }

    @Override
    public List<Map> selectAllAccess() {
        return userMapper.selectAllAccess();
    }

    @Override
    public List<Map> selectExamineInfoById(Integer id) {
        if (id !=0 || id !=null){
            return userMapper.selectExamineInfoById(id);
        }
        return null;
    }

    @Override
    public List<Map> getAllUser() {
        return userMapper.getAllUser();
    }

    @Override
    public List<Map> getUserCreateTime() {
        return userMapper.getUserCreateTime();
    }

    @Override
    public List<Map> selectAccessStatistics(Map map) {
        return userMapper.selectAccessStatistics(map);
    }

    @Override
    public Integer updateUserCodeIdById(Integer id) {
        if (id!=0 || id!=null){
            return userMapper.updateUserCodeIdById(id);
        }
        return null;
    }

    @Override
    public Integer updateRejectById(Integer id) {
        if(id!=0 || id!=null){
            return userMapper.updateRejectById(id);
        }
        return 0;
    }

    @Override
    public User selectAccountById(Integer id) {
        if(id!=0 || id!=null){
            return userMapper.selectAccountById(id);
        }
        return null;
    }

    @Override
    public List<Map> selectUserByCodeNum() {
        return userMapper.selectUserByCodeNum();
    }

    @Override
    public List<Object> selectUserById(Integer id) {
        if (id !=null){
            return userMapper.selectUserById(id);
        }
        return null;
    }

    @Override
    public List<Object> selectUserByType() {
        return userMapper.selectUserByType();
    }

    @Override
    public int selectUserByTypeNum() {
        return userMapper.selectUserByTypeNum();
    }

    @Override
    public Integer updateUserById(Integer id) {
       if (id!=0 || id!=null){
           return userMapper.updateUserById(id);
       }
       return 0;
    }

    @Override
    public Integer lookThroughUserById(Integer id) {
        if(id!=0 || id!=null){
            return userMapper.lookThroughUserById(id);
        }
        return 0;
    }

    public String getVer(String phone) {
        //获取6位数的验证码
        int ver = (int) (Math.random() * 899999) + 100000;
        //发送短信的内容
        String message = "您的验证码为"+ver+"，请于1分钟内正确输入，如非本人操作，请忽略此短信。";
        //获取时间戳
        String timestamp = DateUtil.dateToString(new Date(),"yyyyMMddHHmmss");
        //生成秒嘀签名
        String sign = sign(timestamp);
        //指定返回类型
        String respDataType = "JSON";
        //封装秒嘀请求参数
        String param = packagReqParam(phone, message, timestamp, sign, respDataType);
        //发送请求
        try {
            //将指定格式信息发送给第三方（秒滴）
            //定义变量接收秒滴回复给我们的信息
            String res = send(param);
            //将秒滴响应的信息封装为JSON对象
            JSONObject json = JSONObject.parseObject(res);
            //获取秒滴响应状态码
            String respCode = json.get("respCode").toString();
            if (respCode.equals("00000")) {
                //响应成功，
                long temp  = System.currentTimeMillis();
                Date createtime = new Date(temp);
                Date deadline = new Date(temp+60000);

                userMapper.updateByPhone(String.valueOf(ver),createtime,deadline,phone);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.valueOf(ver);
    }

    @Override
    public Map getUserByPhone(String phone) {
        return userMapper.getUserByPhone(phone);
    }

    @Override
    public List getConcernList(Integer userId) {
        return userMapper.getConcernList(userId);
    }

    @Override
    public Map getUserByOpenid(String openid) {
        return userMapper.getUserByOpenid(openid);
    }

    @Override
    public Integer addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    public int save(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int del(Integer userId, Integer fansId) {
        return userMapper.deleteUserFans(userId,fansId);
    }

    @Override
    public List selectUserListDay() {
        return userMapper.selectUserListDay();
    }

    @Override
    public Map getUserDetailsByUserId(Integer userId) {
        return userMapper.getUserDetailsByUserId(userId);
    }

    @Override
    public int trafficVolumeListener(Integer trafficVolume,Integer userId) {
        return userMapper.trafficVolumeListener(trafficVolume,userId);
    }

    @Override
    public List getFansByUserId(Integer userId) {
        return userMapper.getFansByUserId(userId);
    }

    @Override
    public int addUserFans(UserFans userFans) {
        return userMapper.addUserFans(userFans);
    }

    @Override
    public Integer getConcernCount(Integer userId) {
        return userMapper.getConcernCount(userId);
    }

    @Override
    public Integer getFansCount(Integer userId) {
        return userMapper.getFansCount(userId);
    }

    @Override
    public List getFansList(Integer userId) {
        return userMapper.getFansList(userId);
    }

    private String send(String param) throws Exception {
        //1.封装请求地址
        URL url = new URL(MessageUtil.URL);
        //2.获取连接
        URLConnection urlConnection = url.openConnection();
        //3.设置连接超时时间以及是否可以输入和输出
        urlConnection.setConnectTimeout(3000);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        //4.获取输出流，并转换为字符流，加入缓冲流，并设置字符集编码为UTF-8
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
        //5.发送数据给秒滴
        bw.write(param);
        bw.flush();
        //6.获取输入流，并转换为字符流，加入缓冲流，并设置字符集编码为UTF-8
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        //7.获取秒滴的返回结果
        StringBuffer sb = new StringBuffer();
        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        bw.close();
        return sb.toString();
    }

    /**
     * 生成秒嘀平台签名
     * @param timestamp
     * @return
     */
    private String sign(String timestamp) {
        //1.获取到固定的accountSid和auth_token
        String accountSid = MessageUtil.ACCOUNTSID;
        String auth_token = MessageUtil.AUTHTOKEN;
        //2.使用MD5加密生成签名
        return DigestUtils.md5DigestAsHex((accountSid + auth_token + timestamp).getBytes());
    }

    /**
     * 封装秒嘀请求参数
     * @param phone
     * @param smsContent
     * @param timestamp
     * @param sig
     * @param respDataType
     * @return
     */
    private String packagReqParam(String phone, String smsContent, String timestamp, String sig, String respDataType) {
        StringBuilder sb = new StringBuilder();
        sb.append("accountSid=")
                .append(MessageUtil.ACCOUNTSID)
                .append("&smsContent=")
                .append(smsContent)
                .append("&to=")
                .append(phone)
                .append("&timestamp=")
                .append(timestamp)
                .append("&sig=")
                .append(sig)
                .append("&respDataType=")
                .append(respDataType);
        return sb.toString();
    }
}
